/**
 * Created by jiachenpan on 16/11/18.
 */

export function isvalidUsername(str) {
  const valid_map = ['admin', 'editor']
  return valid_map.indexOf(str.trim()) >= 0
}

/* 合法uri*/
export function validateURL(textval) {
  const urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
  return urlregex.test(textval)
}

/*合并行 */
export function mergeTableRow(data, merge) {
  if (!merge || merge.length === 0) {
    return data
  }
  merge.forEach((m) => {
      const mList = {}
      data = data.map((v, index) => {
        const rowVal = v[m]
        if (mList[rowVal] && mList[rowVal].newIndex === index) {
          mList[rowVal]['num']++
          mList[rowVal]['newIndex']++
          data[mList[rowVal]['index']][m + '-span'].rowspan++
          v[m + '-span'] = {
            rowspan: 0,
            colspan: 0
          }
        } else {
          mList[rowVal] = { num: 1, index: index, newIndex: index + 1 }
          v[m + '-span'] = {
            rowspan: 1,
            colspan: 1
          }
        }
        return v
      })
    })
  return data

}

/* 小写字母*/
export function validateLowerCase(str) {
  const reg = /^[a-z]+$/;
  return reg.test(str)
}

/* 大写字母*/
export function validateUpperCase(str) {
  const reg = /^[A-Z]+$/;
  return reg.test(str)
}

/* 大小写字母*/
export function validateAlphabets(str) {
  const reg = /^[A-Za-z]+$/;
  return reg.test(str)
}

/* 数字与字母*/
export function validateAlphanumeric(str, min, max) {
  const reg = new RegExp('^(?![^A-z]+$)(?!\\D+$)[A-z\\d]{' + min + ',' + max + '}$');
  return reg.test(str)
}

/* 可以输入字母、数字*/
export function validateAlphaOrnumeric(str, min, max) {
  const reg = new RegExp('^[A-z\\d]{' + min + ',' + max + '}$');
  return reg.test(str)
}

/* 首个字母，剩下的数字或字母，数字与字母*/
export function validateFirstAlphanumeric(str, min, max) {
  const reg = new RegExp('^[a-zA-Z](?!\\D+$)[A-z\\d]{' + (min - 1) + ',' + (max - 1) + '}$');
  return reg.test(str)
}

/* 手机号码*/
export function validateMobile(str) {
  const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
  return reg.test(str)
}

/* 电话号码*/
export function validatePhone(str) {
  const reg = /^((0\d{2,3})-)?(\d{7,8})(-(\d{3,4}))?$/;
  return reg.test(str)
}

/* 邮箱*/
export function validatePostbox(str) {
  const reg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
  return reg.test(str)
}

/* 版本号*/
export function validateVersion(str) {
  const reg = /^\d+\.\d+\.\d+$/;
  return reg.test(str)
}

/* 格式化时间*/
export function formattingTime(str, boot) {
  if (!str) return ' ';
  if (typeof str !== 'number') { return str; }
  const datee = new Date(str).toJSON();
  const date = new Date(+new Date(datee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
  return boot ? date.split(' ')[0] : date;
}

/**
 * validate email
 * @param email
 * @returns {boolean}
 */
export function validateEmail(email) {
  const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  return re.test(email)
}

/*
* 金额
* 小数点只能输入9位数，点后面2位
* */
export function validateMoney(money) {
  const reg = /^(\d{0,5}.\d{0,3})(\.\d{1,2})?$/;
  return reg.test(money)
}

/*
 * 比例 100
 * */
export function validateRatio(ratio) {
  /* var le=/^(\d{0,3}.\d{0,3})(\.\d{1,2})?$/*/
  const reg = /^((\d|[1-9]\d|100)|.)(\.\d{1,2})?$/;
  return reg.test(ratio)
}
export function validateRatioContinuous(e) {
  let inl = e;
  if (e !== '') {
    inl = String(e).indexOf('.');
    if (String(e * 1).indexOf('.') === inl) {
      inl = e * 1;
    } else {
      inl = e
    }
  }
  inl * 1 > 100 ? inl = '100.00' : inl
  return inl;
}
/*
*  校验IP
* */
export function isValidIP(ip) {
  const reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
  return reg.test(ip);
}
export function fileTypeback(type,file){
  const typeStr =[]
  if(!type){
    type='img'
  }
  let types = type.split(",")
  for(const t in types){
    typeStr.push(types[t])
  }
  const fileName = file.name;
  const m = fileName.match(/\.(\w+)(#|\?|$)/);
  const fileType = (m && m[1]).toString().toLowerCase();
  const allowHook = {
    video: ['mp4', 'ogv', 'ogg', 'webm'],
    audio: ['wav', 'mp3', 'ogg', 'acc', 'webm', 'amr'],
    file: [ 'pdf'],//'doc', 'docx', 'xlsx', 'xls',
    excel: ['xlsx', 'xls'],
    img: ['jpg', 'jpeg', 'png', 'gif']
  }
  let typefile='img'
  for(const k in typeStr){
    let typea = typeStr[k]
    if((allowHook[typea] || []).includes(fileType)){
      typefile = typea
    }
  }
  return typefile
}
/*
*  校验上传文件
* */
export function validUploadFile(type, file) {
  const typeStr =[]
  if(!type){
    type='img'
  }
  let types = type.split(",")
  for(const t in types){
    typeStr.push(types[t])
  }

  // if (!file) {
  //   file = type;
  //   type = 'img'
  // }
  const fileName = file.name;
  const m = fileName.match(/\.(\w+)(#|\?|$)/);
  const fileType = (m && m[1]).toString().toLowerCase();
  const allowHook = {
    video: ['mp4', 'ogv', 'ogg', 'webm'],
    audio: ['wav', 'mp3', 'ogg', 'acc', 'webm', 'amr'],
    file: [ 'pdf'],//'doc', 'docx', 'xlsx', 'xls',
    excel: ['xlsx', 'xls'],
    img: ['jpg', 'jpeg', 'png', 'gif']
  }
  let validType = false;
  let typefile='img'
  for(const k in typeStr){
    let typea = typeStr[k]
    validType = validType || (allowHook[typea] || []).includes(fileType);
    if((allowHook[typea] || []).includes(fileType)){
      typefile = typea
    }
  }
   //(allowHook[type] || []).includes(fileType);
  if (!validType) {
    const supprtTypes = allowHook[typefile].join(',');
    return `只支持${supprtTypes}类型文件上传`;
  }
  if (fileName.indexOf('%') > -1 || fileName.indexOf('&') > -1) {
    return '上传文件名称不能带有字符"%","&"';
  }
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (typefile === file && !isLt10M) {
    this.$message.error('上传资料大小不能超过 10MB!');
    return false;
  }
  return '';
}
// element accept限制上传的文件格式
export function acceptFile(e, e2) {
  const allowHook = {
    video: '.mp4,.ogv,.ogg,.webm',
    audio: '.wav,.mp3,.ogg,.acc,.webm,.amr',
    file: '.pdf',//doc,.docx,.xlsx,.xls,
    excel: '.xlsx,.xls',
    img: '.jpg,.jpeg,.png,.gif'
  }
  if (e && !e2) {
    return allowHook[e];
  }
  if (e && e2) {
    return allowHook[e] + ',' + allowHook[e2];
  }
  const arr = [];
  for (const k in allowHook) {
    arr.push(allowHook[k]);
  }
  return arr.join(',');
}
